from flask_restful import Resource, reqparse
from flask import request
from models import db, User
from utils import api_response

class UserList(Resource):
    def get(self):
        """获取用户列表"""
        parser = reqparse.RequestParser()
        parser.add_argument('page', type=int, default=1, location='args')
        parser.add_argument('size', type=int, default=10, location='args')
        parser.add_argument('openid', type=str, location='args')  # 添加openid查询参数
        args = parser.parse_args()
        
        # 如果提供了openid参数，则按openid查询
        if args['openid']:
            user = User.query.filter_by(openid=args['openid']).first()
            if user:
                return api_response(user.to_dict())
            else:
                return api_response({'message': '用户不存在'}, code=404)
        
        # 否则返回用户列表
        users = User.query.paginate(
            page=args['page'], 
            per_page=args['size'], 
            error_out=False
        )
        
        return api_response({
            'total': users.total,
            'page': args['page'],
            'size': args['size'],
            'users': [user.to_dict() for user in users.items]
        })
    
    def post(self):
        """创建用户"""
        parser = reqparse.RequestParser()
        parser.add_argument('openid', type=str, required=True, help='微信openid不能为空')
        parser.add_argument('nickname', type=str)
        parser.add_argument('avatar_url', type=str)
        parser.add_argument('gender', type=int)
        parser.add_argument('country', type=str)
        parser.add_argument('province', type=str)
        parser.add_argument('city', type=str)
        parser.add_argument('language', type=str)
        args = parser.parse_args()
        
        # 检查openid是否已存在
        existing_user = User.query.filter_by(openid=args['openid']).first()
        if existing_user:
            return api_response({'message': '用户已存在'}, code=400)
        
        user = User(
            openid=args['openid'],
            nickname=args['nickname'],
            avatar_url=args['avatar_url'],
            gender=args['gender'],
            country=args['country'],
            province=args['province'],
            city=args['city'],
            language=args['language']
        )
        
        db.session.add(user)
        db.session.commit()
        
        return api_response(user.to_dict(), message='用户创建成功')

class UserDetail(Resource):
    def get(self, user_id):
        """获取用户详情"""
        user = User.query.get(user_id)
        if not user:
            return api_response({'message': '用户不存在'}, code=404)
        
        return api_response(user.to_dict())
    
    def put(self, user_id):
        """更新用户信息"""
        user = User.query.get(user_id)
        if not user:
            return api_response({'message': '用户不存在'}, code=404)
        
        parser = reqparse.RequestParser()
        parser.add_argument('nickname', type=str)
        parser.add_argument('avatar_url', type=str)
        parser.add_argument('gender', type=int)
        parser.add_argument('country', type=str)
        parser.add_argument('province', type=str)
        parser.add_argument('city', type=str)
        parser.add_argument('language', type=str)
        args = parser.parse_args()
        
        # 更新字段
        if args['nickname'] is not None:
            user.nickname = args['nickname']
        if args['avatar_url'] is not None:
            user.avatar_url = args['avatar_url']
        if args['gender'] is not None:
            user.gender = args['gender']
        if args['country'] is not None:
            user.country = args['country']
        if args['province'] is not None:
            user.province = args['province']
        if args['city'] is not None:
            user.city = args['city']
        if args['language'] is not None:
            user.language = args['language']
        
        db.session.commit()
        
        return api_response(user.to_dict(), message='用户信息更新成功')
    
    def delete(self, user_id):
        """删除用户"""
        user = User.query.get(user_id)
        if not user:
            return api_response({'message': '用户不存在'}, code=404)
        
        db.session.delete(user)
        db.session.commit()
        
        return api_response(None, message='用户删除成功')